// useModal.js
import { h, createApp,ref,nextTick   } from 'vue'
import ModalContainer from '@/components/ModalContainer.vue'


/**
 * 创建弹窗内容
 * @param {*} content 弹窗组件实例
 * @param {*} options 
 * @returns 
 */
export function createModal(content, options = {}) {
  const {
    /**业务组件接收参数 */
    props: contentProps = {},
    /**业务组件回调事件 */
    on: contentEvents = {},
    html = false,
    /**弹窗配置 */
    config = {}
  } = options

  /**弹窗DOM */
  const container = document.createElement('div')
  document.body.appendChild(container)

  let isClosed = false
  const show = ref(true) // 使用 ref 创建响应式 show

  const contentRef = ref(null);

  //关闭弹窗
  const close = () => {
    if (isClosed) return
    show.value = false
    isClosed = true
  }


  const modalApp = createApp({
    render() {
      return h(
        ModalContainer,
        /**传递给弹窗的参数 */
        {
          show: show.value,
          ...config,
          /**弹窗关闭事件（不需要用户配置）*/
          onClose: close,
          /**弹窗关闭回调（不需要用户配置）*/
          onAfterClose: () => {
            modalApp.unmount()
            document.body.removeChild(container)
          },
          /** 弹窗确认事件 */
          onConfirm: async () => {
            await nextTick(); // 等待 DOM 更新循环结束
            if (contentRef.value) {
                // 调用组件实例的 getCallbackData 方法，给弹窗确认事件提供数据源
                const instance = contentRef.value;
                if (typeof instance.getCallbackData === 'function') {
                    const data = await instance.getCallbackData();
                    config.success?.(data.value);
                }else{
                  config.success?.();
                }

                //不在这里处理关闭，由调用方处理
            }
            
        }
          
        },
        [
          html 
            ? h('div', { innerHTML: content,ref: contentRef })  //展示纯HTML
            : h(content, {
                ...contentProps,
                ...contentEvents,
                ref: contentRef,
              })
        ]
      )
    }
  })

  const modalInstance = modalApp.mount(container)

  /**hooks暴露 */
  return {
    close,
    instance: modalInstance
  }
}